package socket;

import org.xsocket.DataConverter;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;

class EchoHandler implements IDataHandler {

    public boolean onData(INonBlockingConnection nbc)
            throws IOException,
            BufferUnderflowException,
            MaxReadSizeExceededException {

//        String data = nbc.readStringByDelimiter("\r\n");
//        String data = nbc.readStringByLength(512);
//        String data = new String(bytes, "utf-8").trim();
        ByteBuffer copyBuffer = ByteBuffer.allocate(200);

        nbc.read(copyBuffer);
        copyBuffer.flip();
        String data = DataConverter.toString(copyBuffer, "utf-8");

        System.out.println(data);
        nbc.write(data + "\r\n");
        nbc.flush();
        return true;
    }

    public static void main(String[] args) throws IOException {
        // creates the server by passing over the port number & handler
        IServer srv = new Server(2000, new EchoHandler());

// run it within the current thread.
//        srv.run();  // the call will not return

// ... or start it by using a dedicated thread
        srv.start(); // returns after the server has been started
    }
}